package portal.dao;

import dao.PublicDao;
import dao.Query;
import dao.QueryCallBackList;
import net.CommitJob;
import net.sf.json.JSONObject;
import portal.beans.Job;
import portal.mybatis.dao.JobEntity;
import portal.mybatis.dao.service.JobDetailService;
import utils.UserLogUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Component
public class ScheduleJobDetailDao {
	@Autowired
   private JobDetailService jobDetailService;
	public boolean insertScheduleJobDetail(CommitJob commitJob, Job job, String jobStatues, String executeFilePath,
			String jobSlotQuantity, String executionHost, String cpuUsage) {
		JSONObject startInfo = JSONObject.fromObject(commitJob);	
		//System.out.println("CPUNum::"+job.getCPUkernelNumber());
		
		return jobDetailService.insertJobDetail(job.getJobId(), job.getName(), jobStatues, job.getJobQueue(),
				job.getJobPriority(), job.getStrategy(), job.getCommand(), executeFilePath, Integer.valueOf(jobSlotQuantity),
				job.getMemoryUsage(), job.getCPUkernelNumber()!=null?Integer.valueOf(job.getCPUkernelNumber()):0, startInfo.toString(), executionHost, cpuUsage,
						job.getMPINumber()!=null?Integer.valueOf(job.getMPINumber()):0, job.getDependentFiles());
		
	}
	@Deprecated
	public boolean insertScheduleJobDetail1(CommitJob commitJob, Job job, String jobStatues, String executeFilePath,
			String jobSlotQuantity, String executionHost, String cpuUsage) {
		String sql = "insert into `schedule_job_detail`(job_id,job_name,job_status,job_sequence,job_priority,"
				+ "schedule_strategy,submit_time,start_time,command,execute_file_path,job_slot_quantity,used_memory,"
				+ "occupied_cpu_quantity,start_info,execute_host,cpu_usage,mpi_processors_quantity,dependent_files) values (?,?,?,?,?,?,"
				+ "now(),now(),?,?,?,?,?,?,?,?,?,?) ";
		JSONObject startInfo = JSONObject.fromObject(commitJob);
		Object[] param = new Object[] { job.getJobId(), job.getName(), jobStatues, job.getJobQueue(),
				job.getJobPriority(), job.getStrategy(), job.getCommand(), executeFilePath, jobSlotQuantity,
				job.getMemoryUsage(), job.getCPUkernelNumber(), startInfo.toString(), executionHost, cpuUsage,
				job.getMPINumber(), job.getDependentFiles() };
		return Query.executeDML(sql, param) > 0;
	}
	@Deprecated
	public boolean updateScheduleJobDetail1(String jobId, String status, String terminationTime, String memUsage,
			String cpuTime, String executionHost, String cpuUsage, String remainMem) {
		String sql = "update `schedule_job_detail` set job_status=?,end_time=?,used_memory=?,cpu_executed_time=?,"
				+ "execute_host=?,cpu_usage=?,remain_mem=? where job_id=?";

		if (memUsage == null || memUsage == "null" || memUsage.equals("null")) {
			memUsage = "0M";
		}
		Object[] params = new Object[] { status, terminationTime, memUsage, cpuTime, executionHost, cpuUsage, remainMem,
				jobId };
		return Query.executeDML(sql, params) > 0;
	}
	public boolean updateScheduleJobDetail(String jobId, String status, String terminationTime, String memUsage,
			String cpuTime, String executionHost, String cpuUsage, String remainMem) {
		return jobDetailService.updateScheduleJobDetail(jobId,status,terminationTime,memUsage,cpuTime,  executionHost,  cpuUsage, remainMem );
	}

	/**
	 * 根据jobId，查询是否在schedule_job_detail中 By黄振
	 */
	@Deprecated
	public boolean isScheduleJobByJobId(String jobId) {
		String sql = "select count(*) from schedule_job_detail where job_id = ?";
		Object[] params = new Object[] { jobId };
		return PublicDao.oneNum(sql, params) > 0;
	}

	/**
	 * 查询所有job By 黄振
	 * 
	 * @param userId
	 * @param onePageCount
	 * @param currentPage
	 * @return
	 */
	@Deprecated
	public List<Object> getJobDetails(String userId, Integer onePageCount, Integer currentPage) {
		String sql = "select * from schedule_job_detail where is_delete = 0 order by submit_time desc limit "
				+ (currentPage - 1) * onePageCount + " , " + onePageCount;
		List<Object> jobDetails = new ArrayList<>();
		jobDetails = Query.executeQueryList(jobDetails, sql, null, new QueryCallBackList() {
			@Override
			public List<Object> doExecuteList(ResultSet rs, List<Object> results) {
				try {
					while (rs.next()) {
						Job job = new Job();
						job.setJobId(rs.getString("job_id"));
						job.setName(rs.getString("job_name"));
						job.setJobStatus(rs.getString("job_status"));
						job.setJobQueue(rs.getString("job_sequence"));
						job.setJobPriority(rs.getString("job_priority"));
						job.setStrategy(rs.getString("schedule_strategy"));
						job.setSubmitTime(rs.getString("submit_time"));
						job.setEndTime(rs.getString("end_time"));
						job.setStartTime(rs.getString("start_time"));
						job.setCommand(rs.getString("command"));
						job.setFileUri(rs.getString("execute_file_path"));
						job.setJobSlotQuantity(rs.getString("job_slot_quantity"));
						job.setMemoryUsage(rs.getString("used_memory"));
						job.setCPUkernelNumber(rs.getString("occupied_cpu_quantity"));
						job.setStartInfo(rs.getString("start_info"));
						job.setExecutionHost(rs.getString("execute_host"));
						job.setCpuUsage(rs.getString("cpu_usage"));
						job.setRemainMem(rs.getString("remain_mem"));
						results.add(job);
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
				return results;
			}
		});
		return jobDetails;
	}

	/**
	 * 根据每页数量计算总页数 By黄振
	 *
	 * @param onePageCount
	 * @return
	 */
	@Deprecated
	public int getJobPageNum(Integer onePageCount) {
		int jobNum = this.getJobNum();
		return (jobNum % onePageCount) == 0 ? (jobNum / onePageCount) : (jobNum / onePageCount + 1);
	}

	/**
	 * 获取所有的Job数量 By黄振
	 *
	 * @return
	 */
	@Deprecated
	public synchronized int getJobNum() {
		String sql = "select count(*) from schedule_job_detail where is_delete = 0";
		return PublicDao.oneNum(sql, null);
	}

	/**
	 * 通过作业名称查询作业信息
	 * 
	 * @param jobName
	 * @return
	 */
	@Deprecated
	public List<Object> getJobDetailsByJobName(String jobName, Integer onePageCount, Integer currentPage) {
		String sql = "select * from schedule_job_detail where job_name=? and is_delete = 0  order by submit_time desc limit "
				+ (currentPage - 1) * onePageCount + " , " + onePageCount;
		List<Object> jobDetails = new ArrayList<>();
		jobDetails = Query.executeQueryList(jobDetails, sql, new Object[] { jobName }, new QueryCallBackList() {
			@Override
			public List<Object> doExecuteList(ResultSet rs, List<Object> results) {
				try {
					while (rs.next()) {
						Job job = new Job();
						job.setJobId(rs.getString("job_id"));
						job.setName(rs.getString("job_name"));
						job.setJobStatus(rs.getString("job_status"));
						job.setJobQueue(rs.getString("job_sequence"));
						job.setJobPriority(rs.getString("job_priority"));
						job.setStrategy(rs.getString("schedule_strategy"));
						job.setSubmitTime(rs.getString("submit_time"));
						job.setEndTime(rs.getString("end_time"));
						job.setStartTime(rs.getString("start_time"));
						job.setCommand(rs.getString("command"));
						job.setFileUri(rs.getString("execute_file_path"));
						job.setJobSlotQuantity(rs.getString("job_slot_quantity"));
						job.setMemoryUsage(rs.getString("used_memory"));
						job.setCPUkernelNumber(rs.getString("occupied_cpu_quantity"));
						job.setStartInfo(rs.getString("start_info"));
						job.setExecutionHost(rs.getString("execute_host"));
						job.setCpuUsage(rs.getString("cpu_usage"));
						job.setRemainMem(rs.getString("remain_mem"));
						results.add(job);
					}
				} catch (SQLException e) {
					e.printStackTrace();
				}
				return results;
			}
		});
		return jobDetails;
	}
	@Deprecated
	public int getJobPageNumByJobName(Integer onePageCount, String jobName) {
		int jobNum = this.getJobNumByJobName(jobName);
		return (jobNum % onePageCount) == 0 ? (jobNum / onePageCount) : (jobNum / onePageCount + 1);
	}
	@Deprecated
	public synchronized int getJobNumByJobName(String jobName) {
		String sql = "select count(*) from schedule_job_detail where job_name = ? and is_delete = 0 ";
		return PublicDao.oneNum(sql, new Object[] { jobName });
	}

	/**
	 * 更新schedule_job_detail表中的作业状态
	 * 
	 * @return
	 */
	public boolean updateStateById(String status, String jobId) {
		return jobDetailService.updateStateById(status, jobId);
	}
	@Deprecated
	public boolean updateStateById1(String status, String jobId) {

		String sql = "update `schedule_job_detail` set job_status=?,end_time=now() where job_id=?";

		Object[] params = new Object[] { status, jobId };
		return Query.executeDML(sql, params) > 0;

	}

	/**
	 * 用于显示作业详情
	 * 
	 * @param job_id
	 *            对应的作业id
	 * @return
	 */
	@Deprecated
	public synchronized List<Object> getJobDetail(final String job_id) {
		String sql = "SELECT * FROM schedule_job_detail WHERE job_id=?";
		List<Object> results = new ArrayList<>();
		Query.executeQueryList(results, sql, new Object[] { job_id }, new QueryCallBackList() {
			@Override
			public List<Object> doExecuteList(ResultSet rs, List<Object> results) {
				try {
					while (rs.next()) {
						JSONObject oneJob = new JSONObject();
						// 作业基本信息
						oneJob.put("job_id", rs.getString("job_id"));
						oneJob.put("job_name", rs.getString("job_name"));
						oneJob.put("job_status", rs.getString("job_status"));
						oneJob.put("job_sequence", rs.getString("job_sequence"));
						oneJob.put("job_priority", rs.getString("job_priority"));
						oneJob.put("schedule_strategy", rs.getString("schedule_strategy"));
						oneJob.put("submit_time", rs.getString("submit_time"));
						oneJob.put("end_time", rs.getString("end_time"));
						oneJob.put("start_time", rs.getString("start_time"));
						oneJob.put("command", rs.getString("command"));
						oneJob.put("mpi_processors_quantity", rs.getString("mpi_processors_quantity"));
						oneJob.put("dependent_files", rs.getString("dependent_files"));
						oneJob.put("execute_host", rs.getString("execute_host"));
						oneJob.put("execute_file_path", rs.getString("execute_file_path"));
						oneJob.put("job_slot_quantity", rs.getString("job_slot_quantity"));
						oneJob.put("used_memory", rs.getString("used_memory"));
						oneJob.put("occupied_cpu_quantity", rs.getString("occupied_cpu_quantity"));
						oneJob.put("cpu_executed_time", rs.getString("cpu_executed_time"));
						results.add(oneJob);
					}
					return results;
				} catch (SQLException e) {
					e.printStackTrace();
					return results;
				}
			}
		});
		return results;
	}

	/**
	 * 用于获取job_id中的各个节点信息
	 * 
	 * @param job_id
	 *            对应的作业id
	 * @return
	 */
	@Deprecated
	public synchronized List<Object> getNodeList(String job_id) {
		String sql = "SELECT * FROM schedule_node_detail WHERE job_id=?";
		List<Object> results = new ArrayList<>();
		Query.executeQueryList(results, sql, new Object[] { job_id }, new QueryCallBackList() {
			@Override
			public List<Object> doExecuteList(ResultSet rs, List<Object> results) {
				try {
					while (rs.next()) {
						JSONObject oneJob = new JSONObject();
						// 结点基本信息
						oneJob.put("node_id", rs.getString("node_id"));
						oneJob.put("node_name", rs.getString("node_name"));
						results.add(oneJob);
					}
					return results;
				} catch (SQLException e) {
					e.printStackTrace();
					return results;
				}
			}
		});
		return results;
	}

	/**
	 * 用于查询导出作业模板XML的json
	 * 
	 * @param jobId  对应的作业id
	 * @return
	 */

	public synchronized List<Object> getJobXMLJson(final String job_id) {
		List<Object> results = new ArrayList<>();
		JSONObject oneJob = new JSONObject();
		JobEntity job=jobDetailService.selectJobById(job_id);
		if(job!=null){
			//oneJob.put("xml_json", job.getStartInfo());
			oneJob=JSONObject.fromObject(job);
			//oneJob=JSONObject.
			oneJob.put("startInfo", JSONObject.fromObject(oneJob.getString("startInfo")));
			results.add(oneJob);
		}
		return results;
	}
	@Deprecated
	public synchronized List<Object> getJobXMLJson1(final String job_id) {
		String sql = "SELECT start_info FROM schedule_job_detail WHERE job_id=?";
		List<Object> results = new ArrayList<>();
		Query.executeQueryList(results, sql, new Object[] { job_id }, new QueryCallBackList() {
			@Override
			public List<Object> doExecuteList(ResultSet rs, List<Object> results) {
				try {
					while (rs.next()) {
						JSONObject oneJob = new JSONObject();
						// 作业基本信息
						oneJob.put("jobName", rs.getString("job_name"));
						oneJob.put("command", rs.getString("command"));
						oneJob.put("dependentFiles", rs.getString("dependent_files"));
						oneJob.put("scheduleStrategy", rs.getString("schedule_strategy"));
						oneJob.put("jobPriority", rs.getString("job_priority"));
						oneJob.put("jobSequence", rs.getString("job_sequence"));
						oneJob.put("startTime", rs.getString("start_time"));
						oneJob.put("endTime", rs.getString("end_time"));
						oneJob.put("usedMemory", rs.getString("used_memory"));
						oneJob.put("occupiedCpuQuantity", rs.getString("occupied_cpu_quantity"));
						oneJob.put("mpiProcessorsQuantity", rs.getString("mpi_processors_quantity"));
						oneJob.put("params", JSONObject.fromObject(rs.getString("start_info")).get("params"));
						results.add(oneJob);
					}
					return results;
				} catch (SQLException e) {
					e.printStackTrace();
					return results;
				}
			}
		});
		return results;
	}

	@Deprecated
	public boolean deleteJob1(String jobId){
		String sqlDelete = "update `schedule_job_detail` set is_delete = 1 where job_id=?";
		return Query.executeDML(sqlDelete, new Object[]{jobId})==1;
	}
	public boolean deleteJob(String jobId){
		return jobDetailService.updateJobDeleted(1, jobId);
	}

}